let { projectRootPath } = require("../../util/path/index.js");
let {
  executeSql,
  transaction,
  getTotal,
  getByPagination,
  removeByUuid,
  getAll,
} = require(`${projectRootPath}/mysql/index.js`);
let { getUuid } = require(`${projectRootPath}/util/uuid/index.js`);
let { getCurrentDatetime } = require(
  `${projectRootPath}/util/datetime/index.js`,
);
let { getUserByAll, editUserByUuid } = require(
  `${projectRootPath}/service/user/index.js`,
);

// 创建权限
async function createRole(data) {
  let { name } = data;
  return await transaction(async (connection) => {
    let sql = `insert into RoleTable (uuid, name, opDatetime) values ('${getUuid()}', '${name}', '${getCurrentDatetime()}')`;
    await executeSql(connection, sql);
  });
}
// 获取权限分页数据
async function getRoleByPagination(data) {
  let { pageSize, currentPage, name } = data;
  let where = "";
  if (name) {
    where = `where name like '%${name}%'`;
  }
  return await transaction(async (connection) => {
    let list = await getByPagination(
      connection,
      "RoleTable",
      "opDatetime",
      where,
      pageSize,
      currentPage,
    );
    let total = await getTotal(connection, "RoleTable", "opDatetime", where);
    return { list, total };
  });
}
// 通过 uuid 编辑权限
async function editRoleByUuid(data) {
  let { uuid, name } = data;
  return await transaction(async (connection) => {
    let sql = `update RoleTable set name='${name}' where uuid='${uuid}'`;
    await executeSql(connection, sql);
  });
}
// 通过 uuid 删除权限
async function removeRoleByUuid(data) {
  let { uuid } = data;
  return await transaction(async (connection) => {
    await removeByUuid(connection, "RoleTable", uuid);
    let allUser = await getUserByAll();
    allUser = allUser.list.map((user) => {
      return {
        ...user,
        roleUuidList: JSON.stringify(
          JSON.parse(user.roleUuidList).filter((roleUuid) => {
            return roleUuid !== uuid;
          }),
        ),
      };
    });
    for (let i = 0; i < allUser.length; i++) {
      await editUserByUuid(allUser[i]);
    }
  });
}
// 获取全部权限
async function getRoleByAll() {
  return await transaction(async (connection) => {
    let list = await getAll(connection, "RoleTable", "opDatetime");
    return { list };
  });
}
module.exports = {
  createRole,
  getRoleByPagination,
  editRoleByUuid,
  removeRoleByUuid,
  getRoleByAll,
};
